/**
 * 收藏
 */
import api from '../../tools/api'
import {SUCCESS_STATUS} from '../../config/status'
import promise from '../../tools/promise'
import {
  FAVORITE_LIST,
  FAVORITE_CLASS_TREE,
  FAVORITE_CLASS_INFO,
  FAVORITE_SAVEDATA
} from '../mutation-types'

const state = {
  pageData: {
    total: 1,
    per_page: 15,
    current_page: 1,
    last_page: 1
  },
  favoriteList: [],
  classTree: [],
  classInfo: {},
  saveData: {}
}

const mutations = {
  [FAVORITE_LIST] (state, payload) {
    state.favoriteList = payload.data
    state.pageData.total = Number(payload.total)
    state.pageData.per_page = Number(payload.per_page)
    state.pageData.current_page = Number(payload.current_page)
    state.pageData.last_page = Number(payload.last_page)
  },
  [FAVORITE_CLASS_TREE] (state, payload) {
    state.classTree = payload
  },
  [FAVORITE_CLASS_INFO] (state, payload) {
    state.classInfo = payload
  },
  [FAVORITE_SAVEDATA] (state, data) {
    state.saveData = data
  }
}

const actions = {
  // 获取收藏列表
  async favoriteList ({commit}, payload) {
    let listRes = await api('serverfavorite/favorite/Favorite/favoriteList', payload)
    commit(FAVORITE_LIST, listRes.res)
  },
  // 获取收藏分类
  async classTree ({commit}, payload) {
    let treeRes = await api('serverfavorite/favorite/FavoriteCategory/cateList', payload)
    if (SUCCESS_STATUS === treeRes.status) {
      commit(FAVORITE_CLASS_TREE, treeRes.res)
    }
  },
  // 改变分类状态
  async classChange ({commit}, payload) {
    let changeRes = await api('serverfavorite/favorite/FavoriteCategory/changeStatus', payload)
    return promise(changeRes)
  },
  // 删除分类
  async classDel ({commit}, payload) {
    let delRes = await api('serverfavorite/favorite/FavoriteCategory/delOneCate', payload)
    return promise(delRes)
  },
  // 添加分类
  async classAdd ({commit}, payload) {
    let addRes = await api('serverfavorite/favorite/FavoriteCategory/addCate', payload)
    return promise(addRes)
  },
  // 获取分类详情
  async classInfo ({commit}, payload) {
    let infoRes = await api('serverfavorite/favorite/FavoriteCategory/oneCateInfo', payload)
    if (SUCCESS_STATUS === infoRes.status) {
      commit(FAVORITE_CLASS_INFO, infoRes.res)
    }
  },
  // 编辑分类
  async classEdit ({commit}, payload) {
    let editRes = await api('serverfavorite/favorite/FavoriteCategory/editCate', payload)
    return promise(editRes)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
